package com.lagou.rpc.consumer.zk;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 郑样平
 * @date 2021/6/14  19:53
 */
public class ZkServerClient {
    public static List<String> listServer = new ArrayList<>();

    private static int count = 1;

    public static void initServer() {

        final String memberServerPath = "/lg-service";

        // 连接zk，获取服务列表
        // TODO 5s获取一次
        final ZkClient zkClient = new ZkClient("106.75.147.53:2181", 5000, 1000);

        // 从zk获取最新的服务器列表
        List<String> children = zkClient.getChildren(memberServerPath);

        // 刷新本地最新服务器列表
        listServer.clear();
        for (String p : children) {
            listServer.add(zkClient.readData(memberServerPath + "/" + p));
        }

        System.out.println("最新服务信息listServer:" + listServer.toString());

        // 监听服务器列表变化,获取最新列表
        zkClient.subscribeChildChanges(memberServerPath, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> childrens) throws Exception {
                listServer.clear();
                for (String subP : childrens) {
                    listServer.add(zkClient.readData(memberServerPath + "/" + subP));
                }

                System.out.println("服务列表变更了 listServer:" + listServer.toString());
            }
        });
    }

    // 轮询服务器列表
    public static String getServer() {
        if (listServer.size() == 0) {
            return null;
        }

        String serverName = listServer.get(count % listServer.size());
        count++;
        return serverName;
    }

}
